<template>
  <div class="visit-list-container">
    <el-card class="visit-card">
      <template #header>
        <div class="card-header">
          <span>拜访管理</span>
          <div class="header-buttons">
            <el-button type="primary" @click="handleCreate">新增拜访</el-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <el-form :model="queryParams" inline class="query-form">
        <el-form-item label="客户名称">
          <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable />
        </el-form-item>
        <el-form-item label="拜访日期">
          <el-date-picker
            v-model="queryParams.visitDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 拜访列表 -->
      <el-table
    v-loading="loading"
    stripe
    highlight-current-row
    style="width: 100%"
    :data="visitList"
    >
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="formattedVisitTime" label="拜访日期" width="120" />
      <el-table-column prop="visitType" label="拜访类型" width="120">
        <template #default="{ row }">
          {{ getVisitTypeLabel(row.visitType) }}
        </template>
      </el-table-column>
      <el-table-column prop="visitPurpose" label="拜访目的" />
      <el-table-column prop="visitResult" label="拜访结果" />
      <el-table-column prop="createdBy" label="创建人" width="120" />
      <el-table-column prop="visitTime" label="拜访时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.visitTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateAt" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.updateAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>

            <!-- 当状态为计划中时显示状态更新按钮 -->
            <template v-if="row.visitStatusName === '计划中'">
              <el-button type="success" link @click="handleStatusUpdate(row, '已完成')"
                >已完成</el-button
              >
              <el-button type="warning" link @click="handleStatusUpdate(row, '已取消')"
                >已取消</el-button
              >
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.size"
      :total="total"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      />
    </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getVisits, deleteVisit } from '@/api/visit'
import { VisitTypeMap } from '@/types/visit'
import type { Visit } from '@/types/visit'
import axios from 'axios'
import { formatUnixTimestamp } from '@/utils/date'

const router = useRouter()
const loading = ref(false)
const total = ref(0)
const visitList = ref<Visit[]>([])

const queryParams = reactive({
  page: 0,
  size: 10,
  customerName: '',
  visitDate: [],
})

// 获取拜访类型的中文标签
const getVisitTypeLabel = (visitType: string) => {
  return VisitTypeMap[visitType as keyof typeof VisitTypeMap]?.label || visitType
}

const loadData = async () => {
  loading.value = true
  try {
    const res = await getVisits(queryParams)
    visitList.value = res.data.content
    total.value = res.data.totalElements
  } catch (error) {
    console.error('加载拜访列表失败:', error)
    ElMessage.error('加载拜访列表失败')
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.page = 0
  loadData()
}

const resetQuery = () => {
  queryParams.customerName = ''
  queryParams.visitDate = []
  handleQuery()
}

const handleSizeChange = (val: number) => {
  queryParams.size = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  queryParams.page = val
  loadData()
}

// 记录页面访问日志
const recordPageAccess = async () => {
  try {
    await axios.post('/api/logs', {
      action: 'ACCESS_PAGE',
      description: '访问拜访管理页面',
    })
  } catch (error) {
    console.error('记录页面访问日志失败:', error)
  }
}

const handleCreate = () => {
  router.push('/visits/create')
}

const handleEdit = (row: Visit) => {
  router.push(`/visits/${row.id}/edit`)
}

const handleView = (row: Visit) => {
  router.push(`/visits/${row.id}`)
}

const handleDelete = async (row: Visit) => {
  try {
    await ElMessageBox.confirm('确认删除该拜访记录吗？', '提示', {
      type: 'warning',
    })
    await deleteVisit(row.id!)
    // 记录删除日志
    await axios.post('/api/logs', {
      action: 'DELETE_VISIT',
      description: `删除拜访记录：${row.title}`,
    })
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除拜访记录失败:', error)
      ElMessage.error('删除拜访记录失败')
    }
  }
}

// 处理状态更新
const handleStatusUpdate = async (row: Visit, status: string) => {
  try {
    await ElMessageBox.confirm(`确认将拜访状态更新为"${status}"吗？`, '提示', {
      type: 'warning',
    })
    if (status == '已完成') {
      status = 'COMPLETED'
    } else if (status == '已取消') {
      status = 'CANCELLED'
    }

    await axios.put(`/api/visits/${row.id}/status`, {
      visitStatus: status,
    })

    // 记录状态更新日志
    await axios.post('/api/logs', {
      action: 'UPDATE_VISIT_STATUS',
      description: `更新拜访状态：${row.customerName} - ${status}`,
    })

    ElMessage.success('状态更新成功')
    // 重新加载数据
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新拜访状态失败:', error)
      ElMessage.error('更新拜访状态失败')
    }
  }
}

// 格式化时间戳
const formatTime = (timestamp: number | undefined): string => {
  if (!timestamp) return '-'
  return formatUnixTimestamp(timestamp)
}

onMounted(() => {
  loadData()
  recordPageAccess()
})
</script>

<style scoped>
.visit-list-container {
  padding: 20px;
}

.visit-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin: 0 20px;
}

.el-table :deep(th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  height: 50px;
  padding: 8px 0;
}

.el-table :deep(td) {
  padding: 12px 0;
  height: 50px;
}

.el-table :deep(.cell) {
  line-height: 1.5;
  white-space: nowrap;
  padding: 0 12px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}
</style>
